/**
 * 初始化autocompleter组件
 * options说明：
 * tableName 标准代码类型
 * keyValue  标准代码值，可选
 * hiddenId 隐藏框id
 */

(function($) {
	$.fn
			.extend({
				"autocomp" : function(options) {
					var input = $(this);
					var basePath = swProxyBasePath;
					var keyValue=options.keyValue;
					var hid=options.hiddenId;
					var callbackfn=options.callback;
					var orderColumn=options.orderColumn;
					var orderRule=options.orderRule;
					// 如果存在初始化keyValue
					if(typeof(options.keyValue)!=="undefined"){
						var jsonObj = {};
						jsonObj.tableName = options.tableName;
						jsonObj.keyValue =options.keyValue;
						jsonObj.orderRule =orderRule;
						jsonObj.orderColumn =orderColumn;
						$.ajax({
							url : basePath + 'sw/base/para/depParaList',
							data : jsonObj,
							dataType : "json",
							type : "GET",
							contentType : "application/json;charset=utf-8",
							success : function(data) {
								input.val(data[0].codeName);
								$("#"+hid).val(data[0].codeValue);
							}
						});
					}
					
					var jsonObj = {};
					jsonObj.tableName = options.tableName;
					jsonObj.orderRule =orderRule;
					jsonObj.orderColumn =orderColumn;
					//最大一次取5000条数据
					jsonObj.rowNum=5000;
					$.ajax({
								url : basePath + 'sw/base/para/depParaList',
								data : jsonObj,
								dataType : "json",
								type : "GET",
								contentType : "application/json;charset=utf-8",
								success : function(data) {
									// 根据返回参数构造json
									var compJson = [];
									for (var i = 0; i < data.length; i++) {
										compJson[i] = {
											value : data[i].codeValue,
											label : data[i].codeValue + "-"
													+ data[i].codeName
										}
									}
									input.autocompleter({
												source : compJson,
												hiddenId : options.hiddenId,
												callback : function(lable,index,obj) {
													//执行回调函数
													if(callbackfn&&typeof callbackfn =='function'){
														callbackfn(obj.value);
//														eval(callbackfn+"('"+obj.value+"')");
													}
													// 回调事件处理回车下一个动作
//													ecode = event.keyCode ? event.keyCode
//															: event.which ? event.which
//																	: event.charCode;
//													var self = input, form = self
//															.parents('form:eq(0)'), focusable, next, prev;
													// alert(ecode);
//													if (event.shiftKey) {
//														if (ecode == 13) {
//															focusable = form.find('input,a,select,textarea')
//															.filter(':visible').not(':input[readonly]')
//															.not(':input[disabled]');
//															prev = focusable.eq(focusable.index(this) - 1);
//
//															if (prev.length) {
//																
//																prev.focus();
//															}
//														}
//													}else
//													if (ecode == 13) {
//														// 光标移动到下一元素
//														focusable = form
//																.find(
//																		'input,select,textarea')
//																.filter(
//																		':visible')
//																.not(
//																		':input[readonly]')
//																.not(
//																		':input[disabled]');
//														next = focusable
//																.eq(focusable
//																		.index(input) + 1);
//														if (next.length&&!(input.attr("enter")=="no")) {
//															next.focus();
//														} else {
//															return false;
//														}
//
//													}
													
												}
											});
								},
								error : function(xhr) {
									console.log(xhr);
								}
							});

				},
				"autocomp2": function(options) {
		            var input = $(this);
		            var basePath = swProxyBasePath;
		            var keyValue = options.keyValue;
		            var hid = options.hiddenId;
		            var callbackfn = options.callback;
		            var filterCon=options.filterCon;
		            // 如果存在初始化keyValue
		            if (typeof(options.keyValue) !== "undefined") {
		                var jsonObj = {};
		                jsonObj.tableName = options.tableName;
		                jsonObj.keyValue = options.keyValue;
		                jsonObj.filterCon=filterCon;
		                $.ajax({
		                    url: basePath + 'sw/base/para/depParaList',
		                    data: jsonObj,
		                    dataType: "json",
		                    type: "GET",
		                    contentType: "application/json;charset=utf-8",
		                    success: function(data) {
		                        input.val(data[0].codeName);
		                        $("#" + hid).val(data[0].codeValue);
		                    }
		                });
		            }
	
		            var jsonObj = {};
		            jsonObj.tableName = options.tableName;
		            jsonObj.filterCon=filterCon;
		            //最大一次取5000条数据
		            jsonObj.rowNum = 5000;
		            $.ajax({
		                url: basePath + 'sw/base/para/depParaList',
		                data: jsonObj,
		                dataType: "json",
		                type: "GET",
		                contentType: "application/json;charset=utf-8",
		                success: function(data) {
		                    // 根据返回参数构造json
		                    var compJson = [];
		                    for (var i = 0; i < data.length; i++) {
		                        compJson[i] = {
		                            value: data[i].codeValue,
		                            label: data[i].codeValue + "-" + data[i].codeName
		                        }
		                    }
		                    input.autocompleter({
		                        source: compJson,
		                        hiddenId: options.hiddenId,
		                        callback: function(lable, index, obj) {
		                            //执行回调函数
		                            if (callbackfn && typeof callbackfn == 'function') {
		                                callbackfn(obj.value);
		                            }
	
		                        }
		                    });
		                },
		                error: function(xhr) {
		                    console.log(xhr);
		                }
		            });
	
		        },
		        "autocomp3": function(options) {
		            var input = $(this);
		            var basePath = swProxyBasePath;
		            var keyValue = options.keyValue;
		            var hid = options.hiddenId;
		            var callbackfn = options.callback;
		            var filterCon=options.filterCon;
		            // 如果存在初始化keyValue
		            if (typeof(options.keyValue) !== "undefined") {
		                var jsonObj = {};
		                jsonObj.tableName = options.tableName;
		                jsonObj.keyValue = options.keyValue;
		                jsonObj.filterCon=filterCon;
		                $.ajax({
		                    url: basePath + 'sw/base/para/depParaList',
		                    data: jsonObj,
		                    dataType: "json",
		                    type: "GET",
		                    contentType: "application/json;charset=utf-8",
		                    success: function(data) {
		                        input.val(data[0].codeName);
		                        $("#" + hid).val(data[0].codeValue);
		                    }
		                });
		            }
	
		            var jsonObj = {};
		            jsonObj.filterCon=filterCon;
		            //最大一次取5000条数据
		            jsonObj.rowNum = 5000;
		            if (typeof(options.tableName) !== "undefined") {
			            jsonObj.tableName = options.tableName;
			            $.ajax({
			                url: basePath + 'sw/base/para/depParaList',
			                data: jsonObj,
			                dataType: "json",
			                type: "GET",
			                contentType: "application/json;charset=utf-8",
			                success: function(data) {
			                    // 根据返回参数构造json
			                    var compJson = [];
			                    for (var i = 0; i < data.length; i++) {
			                        compJson[i] = {
			                            value: data[i].codeValue,
			                            label: data[i].codeValue + "-" + data[i].codeName
			                        }
			                    }
			                    input.autocompleter({
			                        source: compJson,
			                        hiddenId: options.hiddenId,
			                        callback: function(label, index, obj) {//label 显示的内容  index 0 obj：{label下拉显示的 ,value隐藏值}
			                            //执行回调函数
			                            if (callbackfn && typeof callbackfn == 'function') {
			                            	var adapter = {'id': obj.value, 'key': label};
			                                callbackfn(label,adapter,index);
			                            }
		
			                        }
			                    });
			                },
			                error: function(xhr) {
			                    console.log(xhr);
			                }
			            });
		            }else{
		            	input.autocompleter('destroy');
		            	$.ajax({
			                url: options.myurl,
			                dataType: "json",
			                type: "GET",
			                contentType: "application/json;charset=utf-8",
			                success: function(data) {
			                    // 根据返回参数构造json
			                    var compJson = [];
			                    for (var i = 0; i < data.length; i++) {
			                        compJson[i] = {
			                            value: data[i].codeValue,
			                            label: data[i].codeValue + "-" + data[i].codeName
			                        }
			                    }
			                    input.autocompleter({
			                        source: compJson,
			                        hiddenId: options.hiddenId,
			                        callback: function(label, index, obj) {//label 显示的内容  index 0 obj：{label下拉显示的 ,value隐藏值}
			                            //执行回调函数
			                            if (callbackfn && typeof callbackfn == 'function') {
			                            	var adapter = {'id': obj.value, 'key': label};
			                                callbackfn(label,adapter,index);
			                            }
		
			                        }
			                    });
			                },
			                error: function(xhr) {
			                    console.log(xhr);
			                }
			            });
		            }
		            
	
		        },
		        "autocomplocal": function(options) {
					var input = $(this);
					var keyValue=options.keyValue;
					var hid=options.hiddenId;
					var callbackfn=options.callback;
					var orderColumn=options.orderColumn;
					var orderRule=options.orderRule;
		            var filterCon=options.filterCon;
		            var URL = swProxyBasePath + 'sw/base/para/depParaList?tableName='+options.tableName+'&rowNum=5000';
		            
		        	if(supportLocalStorage){//如果浏览器支持LocalStorage
		        		
		        		var source =_getCache(URL);
		        		if(source){//已经存在本url的缓存
		        			input.autocompleter({
		                        source: source,
		                        hiddenId: options.hiddenId,
		                        callback: function(lable, index, obj) {
		                            //执行回调函数
		                            if (callbackfn && typeof callbackfn == 'function') {
		                                callbackfn(obj.value);
		                            }
	
		                        }
		                    });
		        		}else{
		        			//不存在本url的缓存，从数据库获取
		        			var jsonObj = {};
				            jsonObj.tableName = options.tableName;
				            jsonObj.filterCon=filterCon;
				            //最大一次取5000条数据
				            jsonObj.rowNum = 5000;
				            $.ajax({
				                url: URL,
				                data: jsonObj,
				                dataType: "json",
				                type: "GET",
				                contentType: "application/json;charset=utf-8",
				                success: function(data) {
				                    // 根据返回参数构造json
				                    var compJson = [];
				                    for (var i = 0; i < data.length; i++) {
				                        compJson[i] = {
				                            value: data[i].codeValue,
				                            label: data[i].codeValue + "-" + data[i].codeName
				                        }
				                    }
				                    input.autocompleter({
				                        source: compJson,
				                        hiddenId: options.hiddenId,
				                        callback: function(lable, index, obj) {
				                            //执行回调函数
				                            if (callbackfn && typeof callbackfn == 'function') {
				                                callbackfn(obj.value);
				                            }
			
				                        }
				                    });
				                    //将数据写入loaclstorge缓存
				                    _setCache(URL, compJson);
				                    
				                },
				                error: function(xhr) {
				                    console.log(xhr);
				                }
				            });
		        			
		        		}
		        		
		        	}
		        }
		        
			});
})(jQuery);

//loaclstorge的键
var localStorageKey ='autocompleterKey';
var cache=_loadCache();
/**
 * 判断浏览器是否支持localstorge
 * @returns {Boolean}
 */
function supportLocalStorage() {
	var supported = typeof window.localStorage !== 'undefined';
	if (supported) {
	    try {
	        localStorage.setItem("autocompleter", "autocompleter");
	        localStorage.removeItem("autocompleter");
	    } catch (e) {
	        supported = false;
	    }
	}
	return supported;
}

/**
 * 存储localstorge
 * @param url
 * @param data
 */
function _setCache(url, data) {
    if (!supportLocalStorage) { return; }
    if (url && data) {
        cache[url] = {
            value: data
        };

        // Proccess to localStorage
        try {
              localStorage.setItem(localStorageKey, JSON.stringify(cache));
        } catch (e) {
              var code = e.code || e.number || e.message;
              if (code === 22) {
                _deleteCache();
              } else {
                throw(e);
              }
        }
    }
}

/**
 * 读取localstorge
 * @param url
 * @returns
 */
function _loadCache() {
    if (!supportLocalStorage) { return; }
    var json = localStorage.getItem(localStorageKey) || '{}';
    return JSON.parse(json);
}
/**
 * 获取缓存数据
 * @param url
 * @returns
 */
function _getCache(url) {
    if (!url) { return; }
    var response = (cache[url] && cache[url].value) ? cache[url].value : false;
    return response;
}
/**
 * 删除localstorge
 */
function _deleteCache() {
    try {
        localStorage.removeItem(localStorageKey);
        cache = _loadCache();
    } catch (e) {
        throw(e);
    }
}
